rm(list = ls())

library(tidyverse)
library(data.table)
library(haven)
library(ggplot2)
library(ggthemes)
library(lfe)
library(qs)
library(here)
library(texreg)
library(patchwork)
library(extrafont)
library(ggthemr) # devtools::install_github('cttobin/ggthemr')
ggthemr("light", layout = "plain")

library(cowplot) # version 1.1.1 # devtools::install_github("wilkelab/cowplot")


source(here("code", "functions.R"))


# Load and prepare data ---------------------------------------------------------------
ref_orig <- readxl::read_excel(here("data", "referendum", "px-x-1703030000_101_20240403-171844.xlsx"), skip = 1)
setDT(ref_orig)

#Fill empty values
ref_orig <- ref_orig %>% 
  fill(...1, ...2, .direction = "down")

#Names
names(ref_orig) <- c("bfs19", "name", "code", "date_topic", "Electorate_Size", "Votes_Cast", "ja_prct")

#Remove random stuff at end
max_row <- which(str_detect(ref_orig$bfs19, "Meta")) - 1
ref_orig <- ref_orig[1:max_row,]

# filter to only municipalities (remove kanton/bezirk) and remove special characters for easier merging
ref_orig[ , bezirk_kanton := grepl(">>|- |Schweiz|Ohne Angabe", name)]

setkey(ref_orig, bezirk_kanton)

ref_orig <- ref_orig[.(F)]
ref_orig[ , bezirk_kanton := NULL]

ref_orig[ , name := sub("......", "", name)] # remove some unnecessary text
replace_Char <- c("ä" = "ae", "ö" = "oe", "ü" = "ue", "à" = "a", "á" = "a", "â" = "a", "è" = "e", "é" = "e", "ê" = "e")
ref_orig[ , name := stringr::str_replace_all(name, replace_Char)]

#Remove vote by mail
vote_by_mail <- c("ZH-Ausland-CH", "LU-Ausland-CH",
                  "UR-Ausland-CH", "FR-CH de l'etranger",
                  "BS-Ausland-CH", "AI-Ausland-CH", 
                  "SG-Ausland-CH", "AG-Ausland-CH",
                  "TG-Ausland-CH", "VD-CH de l'etranger",
                  "VS-CH de l'etranger", "GE-CH de l'etranger",
                  "AI-Korrespondenzweg", "GE-autres",
                  "TI-voto per corrispondenza")

ref_orig <- ref_orig[!name %in% vote_by_mail]

refs <- ref_orig[ , unique(date_topic)]

ref_orig[ , date := stringr::str_sub(date_topic, 1L, 10L)]
ref_orig[ , topic := stringr::str_sub(date_topic, 12L, -1L)]

ref_orig$bfs19 <- as.numeric(ref_orig$bfs19)


# Add new bfs codes that didn't exist in bfs19 data ---------------------

# Andi's data for merging 2012 municipality names
region_id <- data.table(read_dta(here("data", "cleaning", "auxiliary_files", "border_region_identifiers_bigotta.dta")))
travel_time <- data.table(read_dta(here("data",  "cleaning", "auxiliary_files", "traveltime_originMUN2012_bordercrossingsMUN.dta")))
id_codes <- fread(here("data", "cleaning", "MuniCodes.csv"), encoding = "UTF-8")

# merge the border region identifiers with the id codes
setkey(id_codes, bfsnr); setkey(region_id, bfsnr)
id_codes <- merge(id_codes, region_id, all.x = T, all.y = F)

# make names with multiple region id all in border region
id_codes[ , BR := max(BR, na.rm = T), by = munname2012]

setkey(id_codes, bfsnr); setkey(region_id, bfsnr)
id_codes <- id_codes %>% left_join(travel_time)


new_munis <- tibble(New = c('Andelfingen', 'Andelfingen', 'Thurnen', 'Thurnen', 'Thurnen', 'Villaz', 'Villaz', 'Prez', 'Prez', 'Prez', 'Bois-d\'Amont', 'Bois-d\'Amont', 'Bois-d\'Amont', 'Welschenrohr-Gaensbrunnen', 'Welschenrohr-Gaensbrunnen', 'Schwende-Ruete', 'Schwende-Ruete', 'Neckertal', 'Neckertal', 'Muntogna da Schons', 'Muntogna da Schons', 'Muntogna da Schons', 'Boeztal', 'Boeztal', 'Boeztal', 'Boeztal', 'Herznach-Ueken', 'Herznach-Ueken', 'Zurzach', 'Zurzach', 'Zurzach', 'Zurzach', 'Zurzach', 'Zurzach', 'Zurzach', 'Zurzach', 'Verzasca', 'Verzasca', 'Verzasca', 'Verzasca', 'Verzasca', 'Tresa', 'Tresa', 'Tresa', 'Tresa', 'Val Mara', 'Val Mara', 'Val Mara', 'Hautemorges', 'Hautemorges', 'Hautemorges', 'Hautemorges', 'Hautemorges', 'Hautemorges', 'Val de Bagnes', 'Val de Bagnes', 'Noble-Contree', 'Noble-Contree', 'Noble-Contree', 'Damphreux-Lugnez', 'Damphreux-Lugnez'), 
             Old = c('Adlikon', 'Humlikon', 'Kirchenthurnen', 'Lohnstorf', 'Muehlethurnen', 'Villaz-Saint-Pierre', 'La Folliaz', 'Corserey', 'Noreaz', 'Prez-vers-Noreaz', 'Arconciel', 'Ependes', 'Senedes', 'Gaensbrunnen', 'Welschenrohr', 'Ruete', 'Schwende', 'Hemberg', 'Oberhelfenschwil', 'Casti-Wergenstein', 'Donat', 'Mathon', 'Boezen', 'Effingen', 'Elfingen', 'Hornussen', 'Herznach', 'Ueken', 'Bad Zurzach', 'Baldingen', 'Boebikon', 'Kaiserstuhl', 'Rekingen', 'Rietheim', 'Ruemikon', 'Wislikofen', 'Vogorno', 'Sonogno', 'Corippo', 'Brione (Verzasca)', 'Frasco', 'Croglio', 'Monteggio', 'Ponte Tresa', 'Sessa', 'Maroggia', 'Melano', 'Rovio', 'Apples', 'Cottens', 'Pampigny', 'Severy', 'Bussy-Chardonney', 'Reverolle', 'Bagnes', 'Volleges', 'Miege', 'Venthone', 'Veyras', 'Damphreux', 'Lugnez'))

#Note those distances are not 100 percent accurate but were manually checked for whether they're <15, between 15 and 30, >30, or not in BR
new_munis <- new_munis %>% 
  left_join(id_codes %>% mutate(Old = munname2012)) %>% 
  group_by(New) %>% summarise(BR = max(BR, na.rm = T),
                            travelMUNmin = mean(travelMUNmin, na.rm = T))

new_munis <- new_munis %>% left_join(ref_orig %>% 
                         dplyr::select(bfs19, name, date_topic, Electorate_Size, Votes_Cast, ja_prct, date, topic) %>% 
                         rename(New = name) %>% distinct())

# Merge BR, travel distance ---------------------
cb <- qread(here("data", "cb.qs"))

ref_merged <- ref_orig %>% inner_join(cb %>% dplyr::select(bfs19, travelMUNmin, BR) %>% distinct())

ref <- ref_merged %>% bind_rows(new_munis %>% rename(name = New))


###### Create the treatment indicator variables
ref <- ref %>% 
  mutate(year = date %>% year %>% as.numeric) %>% 
  filter(year <= 2017, BR == 1, travelMUNmin < 30) %>% 
  mutate(transition = as.numeric(year %in% 2000:2003),
         free = as.numeric(year >= 2004),
         transition = as.numeric(year %in% 2000:2003),
         border15 = as.numeric(travelMUNmin < 15),
         border30 = as.numeric(travelMUNmin >= 15 & travelMUNmin < 30),
         transBorder15 = border15 * transition,
         freeBorder15 = border15 * free)

ref %>% filter(date == "2005-09-25") %>% pull(date_topic) %>% unique

# Create Immigration Referendums ------------------------------------------
anti_immigrant <- c("2016-02-28 Volksinitiative «Zur Durchsetzung der Ausschaffung krimineller Ausländer (Durchsetzungsinitiative)»",
                    "2014-02-09 Volksinitiative «Gegen Masseneinwanderung»",
                    "2014-11-30 Volksinitiative «Stopp der Überbevölkerung - zur Sicherung der natürlichen Lebensgrundlagen»",
                    "2013-06-09 Asylgesetz (AsylG) (Dringliche Änderungen des Asylgesetzes)",
                    "2010-11-28 Volksinitiative «Für die Ausschaffung krimineller Ausländer»",
                    "2009-11-29 Volksinitiative «Gegen den Bau von Minaretten»",
                    "2008-06-01 Volksinitiative «Für demokratische Einbürgerungen»",
                    "2006-09-24 Änderung des Asylgesetzes",
                    "2006-09-24 Bundesgesetz über die Ausländerinnen und Ausländer",
                    "2002-11-24 Volksinitiative «gegen Asylrechtsmissbrauch»",
                    "2000-09-24 Volksinitiative «für eine Regelung der Zuwanderung»",
                    "1999-06-13 Bundesbeschluss über dringliche Massnahmen im Asyl- und Ausländerbereich",
                    "1999-06-13 Asylgesetz",
                    "1996-12-01 Volksinitiative «gegen die illegale Einwanderung»",
                    "1994-12-04 Bundesgesetz über Zwangsmassnahmen im Ausländerrecht")


pro_immigrant <- c("2017-02-12 Bundesbeschluss über die erleichterte Einbürgerung von Personen der dritten Ausländergeneration",
                     "2004-09-26 Bundesbeschluss über den Bürgerrechtserwerb von Ausländerinnen und Ausländern der dritten Generation",
                     "2004-09-26 Bundesbeschluss über die ordentliche Einbürgerung sowie über die erleichterte Einbürgerung junger Ausländerinnen und Ausländer der zweiten Generation",
                     "1994-06-12 Bundesbeschluss über die Revision der Bürgerrechtsregelung in der Bundesverfassung (Erleichterte Einbürgerung für junge Ausländer)",
                     "2016-06-05 Änderung des Asylgesetzes (AsylG)",
                     "2009-02-08 Weiterführung des Freizügigkeitsabkommens zwischen der CH und der EU sowie über die Genehmigung des Protokolls über die Ausdehnung des Abkommens auf Bulgarien und Rumänien",
                     "2005-09-25 Bundesbeschluss über die Ausdehnung des Personenfreizügigkeitsabkommens auf die neuen EU-Staaten und über die Revision der flankierenden Massnahmen",
                     "2005-06-05 Bundesbeschluss über die Genehmigung und die Umsetzung der bilateralen Abkommen zwischen der Schweiz und der EU über die Assoziierung an Schengen und Dublin"
                   )

ref <- ref %>% 
  mutate(anti_imm_prct = case_when(date_topic %in% anti_immigrant ~ ja_prct,
                                   date_topic %in% pro_immigrant ~ 100-ja_prct,
                                   TRUE ~ NA_real_),
         imm_topics = case_when(date_topic %in% c(pro_immigrant, anti_immigrant) ~ T,
                                TRUE ~ F))


# Create placebo referendums ----------------------------------------------
placebo_topics <- c("1994-02-20 Luftfahrtgesetz", 
                    "1996-03-10 Bundesbeschluss über die Aufhebung der Pflicht zum Ankauf von Brennapparaten und zur Uebernahme von Branntwein",
                    "1999-02-07 Bundesbeschluss betreffend die Verfassungsbestimmung über die Transplantationsmedizin",  
                    "2000-09-24 Volksinitiative «für einen Solarrappen»",
                    "2002-09-22 Volksinitiative «Überschüssige Goldreserven in den AHV-Fonds»", 
                    "2004-11-28 Bundesgesetz über die Forschung an embryonalen Stammzellen",
                    "2005-11-27 Volksinitiative «für Lebensmittel aus gentechnikfreier Landwirtschaft»",
                    "2006-09-24 Volksinitiative «Nationalbankgewinne für die AHV»", 
                    "2008-11-30 Bundesgesetz über die Betäubungsmittel und psychotropen Stoffe",
                    "2009-05-17 Verfassungsartikel «Zukunft mit Komplementärmedizin» (Gegenentwurf zur Volksinitiative «Ja zur Komplementärmedizin»)",
                    "2010-03-07 Volksinitiative «Gegen Tierquälerei und für einen besseren Rechtsschutz der Tiere»",
                    "2013-09-22 Volksinitiative «Ja zur Aufhebung der Wehrpflicht»",
                    "2014-11-30 Volksinitiative «Rettet unser Schweizer Gold (Gold-Initiative)»",
                    "2016-11-27 Volksinitiative «Für den geordneten Ausstieg aus der Atomenergie»",
                    "2017-09-24 Bundesbeschluss über die Ernährungssicherheit")

ref <- ref %>% mutate(placebo_topics = case_when(date_topic %in% placebo_topics ~ T, TRUE ~ F))


# Immigration referendums -------------------------------------------------
## Aggregate at year level -------------------------------------------------
ref_imm <- ref %>% filter(imm_topics)

## This code aggregates data by municipality and year
ref_year_imm <- ref_imm %>%
  group_by(name, year, travelMUNmin, BR, border15, border30, transBorder15, freeBorder15, bfs19, Electorate_Size, imm_topics) %>%
  summarise(anti_imm_prct = mean(anti_imm_prct, na.rm = TRUE), .groups = 'drop') %>% 
  mutate(anti_imm_prct = if_else(is.nan(anti_imm_prct), NA_real_, anti_imm_prct))

#Define 1999-06-13 Bundesbeschluss über dringliche Massnahmen im Asyl- und Ausländerbereich as reference category
entries <- ref_imm %>% arrange(year) %>% pull(date_topic) %>% unique
entries <- c("1999-06-13 Bundesbeschluss über dringliche Massnahmen im Asyl- und Ausländerbereich", entries[-which(str_detect(entries, "Bundesbeschluss über dringliche Massnahmen"))])
ref_imm$date_topic <- factor(ref_imm$date_topic, levels = entries)


ref_year_imm <- ref_year_imm %>% mutate(TR_three = case_when(border15 == T ~ "0-15 Minutes",
                                                             border30 == T ~ "15-30 Minutes",
                                                             TRUE ~ NA_character_))


## DiD -----------------------------------------
#Topic Fixed Effect
mod_did_topicFE <- felm(anti_imm_prct ~ transBorder15 + freeBorder15 | bfs19 + date_topic | 0 | bfs19, 
                        data = ref_imm %>% filter(BR == 1 & travelMUNmin <= 30, imm_topics == T))
mod_did_topicFE %>% summary

mod_did_topicFE_weights <- felm(anti_imm_prct ~ transBorder15 + freeBorder15 | bfs19 + date_topic | 0 | bfs19, w = ref_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T) %>% pull(Electorate_Size), 
                                data = ref_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T))
mod_did_topicFE_weights %>% summary

#Year Fixed Effect
mod_did_yearFE <- felm(anti_imm_prct ~ transBorder15 + freeBorder15 | bfs19 + year | 0 | bfs19, 
                       data = ref_year_imm %>% filter(BR == 1 & travelMUNmin <= 30, imm_topics == T))

mod_did_yearFE_weights <- felm(anti_imm_prct ~ transBorder15 + freeBorder15 | bfs19 + year | 0 | bfs19, w = ref_year_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T) %>% pull(Electorate_Size), 
                               data = ref_year_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T))

mod_did_yearFE %>% summary
mod_did_yearFE_weights %>% summary

## Event Study -------------------------------------------------------------

# Years with immigration referendums
years <- c(1994, 1996, 1999, 2000, 2002, 2004, 2005, 2006, 2008, 2009, 2010, 2013, 2014, 2016, 2017)

# Add new columns
for(y in years) {
  column_name <- paste0("border15_", y)
  ref_year_imm <- ref_year_imm %>%
    mutate(!!column_name := as.integer(year == y) * border15)
}

#Topic event study
mod_es_topic_FE <- felm(anti_imm_prct ~ border15 *  date_topic| bfs19 | 0 | bfs19,
                        data = ref_imm %>% filter(BR == 1 & travelMUNmin <= 30, imm_topics == T))

mod_es_topic_FE_weights <- felm(anti_imm_prct ~ border15 *  date_topic| bfs19 | 0 | bfs19, w = ref_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T) %>% pull(Electorate_Size), 
                                data = ref_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T))


#Year event study
mod_es_year_FE <- felm(anti_imm_prct ~ border15_1994 + border15_1996 + border15_2000 + border15_2002 + border15_2004 + border15_2005 + border15_2006 + border15_2008 + border15_2009 + border15_2010 +
                         border15_2013 + border15_2014 + border15_2016 + border15_2017 | year + bfs19 | 0 | bfs19,
                       data = ref_year_imm %>% filter(BR == 1 & travelMUNmin <= 30, imm_topics == T))

mod_es_year_FE_weights <- felm(anti_imm_prct ~ border15_1994 + border15_1996 + border15_2000 + border15_2002 + border15_2004 + border15_2005 + border15_2006 + border15_2008 + border15_2009 + border15_2010 +
                                 border15_2013 + border15_2014 + border15_2016 + border15_2017 | bfs19 + year | 0 | bfs19, w = ref_year_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T) %>% pull(Electorate_Size), 
                               data = ref_year_imm %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30, imm_topics == T))

mod_es_year_FE %>% summary
mod_es_year_FE_weights %>% summary

## Plot -----------------------------------------------------------------
imm_raw <- ref_year_imm %>% filter(travelMUNmin <= 30, BR == 1) %>% 
  ggplot(aes(x = year, y = anti_imm_prct, color = TR_three, fill = TR_three, shape = TR_three, linetype = TR_three)) + 
  stat_summary(fun.y = mean, geom = "point") + 
  geom_smooth(method = "loess") + 
  geom_vline(xintercept = c(1999, 2004), linetype = "dashed", color = "black") +
  ylab("Anti-Immigrant Vote Share") +
  xlab("Year") +
  theme_minimal() + 
  scale_x_continuous(breaks = seq(1991, 2019, 2), expand = expansion(mult = 0, add = 0.5)) +
  scale_color_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_fill_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"), name = NULL, guide = "legend") +
  scale_shape_manual(values = c(16, 17, 18), name = NULL, guide = "legend") +
  scale_y_continuous(breaks = seq(35, 62, 2)) +
  coord_cartesian(ylim = c(36, 62)) + 
  annotate("text", x = 1996.5, y = 61, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = 61, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2009.75, y = 61, label = "Free Movement", hjust = 0.5) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"),
        axis.title.y = element_text(vjust = 0)) +
  ggtitle("A. Immigration-Related Popular Votes")


imm_did <- ggplot(coef.gg.prep(list(mod_did_yearFE_weights)), aes(x = modelcoef, y = -1*y, xmin = ylo95, xmax = yhi95, color = variable, shape = variable, group = variable)) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  ggstance::geom_linerangeh(position = ggstance::position_dodgev(.25)) +
  ggstance::geom_pointrangeh(aes(xmin = ylo90, xmax = yhi90), size = 1.25, position = ggstance::position_dodgev(.25)) +
  ylab(NULL) +
  scale_y_continuous(breaks = c(-2, -1), labels = c("Transition\nPeriod", "Free\nMovement"), expand = expand_scale(mult = 0, add = 0.5)) +
  scale_color_manual(name = NULL, guide = "none", values = cbPalette[-3]) +
  scale_shape_discrete(name = NULL, guide = "none") +
  xlab("Effect of Border Proximity on Anti-Immigrant Popular Votes") +
  ggtitle("C. Difference-in-Differences Estimates") +
  theme_bw() + 
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"))


event_study_dat <- data.frame(
  y = coef(mod_es_year_FE_weights),
  ymin = coef(mod_es_year_FE_weights) - qt(.975, df = df.residual(mod_es_year_FE_weights))*sqrt(diag(vcov(mod_es_year_FE_weights))),
  ymax = coef(mod_es_year_FE_weights) + qt(.975, df = df.residual(mod_es_year_FE_weights))*sqrt(diag(vcov(mod_es_year_FE_weights))),
  Year = as.numeric(gsub("border[[:digit:]][[:digit:]]_", "", names(coefficients(mod_es_year_FE_weights))))
)

event_study_dat <- rbind(setDT(event_study_dat), data.table(c(0), c(0), c(0), c(1999)), use.names = F)

imm_es <- ggplot(data = event_study_dat, aes(x = Year, y = y, ymin = ymin, ymax = ymax, 
                                             color = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1))),
                                             shape = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1)))
                                             )) + 
  geom_vline(xintercept = c(1999, 2004), linetype = 2, color = "black") +
  geom_hline(yintercept = 0, linetype = 2, color = "black") +
  geom_pointrange() +
  annotate("text", x = 1995.5, y = 13, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = 13, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2009.75, y = 13, label = "Free Movement", hjust = 0.5) +
  scale_color_manual(values = cbPalette[c(1,2,8)], name = NULL, labels = c("Free Movement", "Transition", "Pre-Reform"), guide = guide_legend(reverse = T)) +
  scale_shape_manual(values = c(16, 17, 18), 
                     name = NULL, 
                     labels = c("Free Movement", "Transition", "Pre-Reform"), 
                     guide = guide_legend(reverse = T)) + 
  ylab("Change in Anti-Immigrant Vote Share") +
  theme_minimal() + 
  scale_x_continuous(breaks = seq(1991, 2019,2)) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt")) +
  ggtitle("B. Effect of Border Proximity By Year")


plots = align_patches(imm_raw, imm_did)
top_row = plot_grid(plots[[1]], imm_es, align = "h")
pdf(here("figures", "Referendums_Immigration.pdf"), height = 8.27, width = 11.69)
plot_grid(top_row, plots[[2]], ncol = 1, rel_heights = c(3, 1.5))
dev.off()

#Placebo  -------------------------------------------------------------
## Aggregate at year level -------------------------------------------------
ref_placebo <- ref %>% filter(placebo_topics)

## This code aggregates data by municipality and year
ref_year_placebo <- ref_placebo %>%
  group_by(name, year, travelMUNmin, BR, border15, border30, transBorder15, freeBorder15, bfs19, Electorate_Size, imm_topics) %>%
  summarise(placebo_prct = mean(ja_prct, na.rm = TRUE), .groups = 'drop') %>% 
  mutate(placebo_prct = if_else(is.nan(placebo_prct), NA_real_, placebo_prct))

ref_year_placebo <- ref_year_placebo %>% mutate(TR_three = case_when(border15 == T ~ "0-15 Minutes",
                                                             border30 == T ~ "15-30 Minutes",
                                                             TRUE ~ NA_character_))

#Define reference category
entries <- ref_placebo %>% arrange(year) %>% pull(date_topic) %>% unique
entries <- c("1999-02-07 Bundesbeschluss betreffend die Verfassungsbestimmung über die Transplantationsmedizin", entries[-which(entries=="1999-02-07 Bundesbeschluss betreffend die Verfassungsbestimmung über die Transplantationsmedizin")])
ref_placebo$date_topic <- factor(ref_placebo$date_topic, levels = entries)


## DiD -----------------------------------------
#Year Fixed Effect
mod_did_yearFE_placebo <- felm(placebo_prct ~ transBorder15 + freeBorder15 | bfs19 + year | 0 | bfs19, 
                       data = ref_year_placebo %>% filter(BR == 1 & travelMUNmin <= 30))

mod_did_yearFE_weights_placebo <- felm(placebo_prct ~ transBorder15 + freeBorder15 | bfs19 + year | 0 | bfs19, w = ref_year_placebo %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30) %>% pull(Electorate_Size), 
                               data = ref_year_placebo %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30))

mod_did_yearFE_placebo %>% summary
mod_did_yearFE_weights_placebo %>% summary

## Event Study -------------------------------------------------------------
# Years with immigration referendums
years <- c(1994, 1996, 1999, 2000, 2002, 2004, 2005, 2006, 2008, 2009, 2010, 2013, 2014, 2016, 2017)

# Add new columns
for(y in years) {
  column_name <- paste0("border15_", y)
  ref_year_placebo <- ref_year_placebo %>%
    mutate(!!column_name := as.integer(year == y) * border15)
}


#Year event study
mod_es_year_FE_placebo <- felm(placebo_prct ~ border15_1994 + border15_1996 + border15_2000 + border15_2002 + border15_2004 + border15_2005 + border15_2006 + border15_2008 + border15_2009 + border15_2010 +
                         border15_2013 + border15_2014 + border15_2016 + border15_2017 | year + bfs19 | 0 | bfs19,
                       data = ref_year_placebo %>% filter(BR == 1 & travelMUNmin <= 30))

mod_es_year_FE_weights_placebo <- felm(placebo_prct ~ border15_1994 + border15_1996 + border15_2000 + border15_2002 + border15_2004 + border15_2005 + border15_2006 + border15_2008 + border15_2009 + border15_2010 +
                                 border15_2013 + border15_2014 + border15_2016 + border15_2017 | bfs19 + year | 0 | bfs19, w = ref_year_placebo %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30) %>% pull(Electorate_Size), 
                               data = ref_year_placebo %>% filter(!is.na(Electorate_Size) & BR == 1 & travelMUNmin <= 30))

mod_es_year_FE_placebo %>% summary
mod_es_year_FE_weights_placebo %>% summary


## ES Plot -----------------------------------------------------------------
placebo_raw <- ref_year_placebo %>% filter(travelMUNmin <= 30, BR == 1) %>% 
  ggplot(aes(x = year, y = placebo_prct, color = TR_three, fill = TR_three, shape = TR_three, fill = TR_three)) + 
  stat_summary(fun.y = mean, geom = "point") + 
  geom_smooth(method = "loess") + 
  geom_vline(xintercept = c(1999, 2004), linetype = "dashed", color = "black") +
  ylab("Placebo Vote Share") +
  xlab("Year") +
  theme_minimal() + 
  scale_x_continuous(breaks = seq(1991, 2019, 2), expand = expansion(mult = 0, add = 0.5)) +
  scale_color_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_fill_manual(values = cbPalette[-3], name = NULL, guide = "legend") +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"), name = NULL, guide = "legend") +
  scale_shape_manual(values = c(16, 17, 18), name = NULL, guide = "legend") +
  scale_y_continuous(breaks = seq(20, 78, 5)) +
  coord_cartesian(ylim = c(35, 78)) + 
  annotate("text", x = 1996.5, y = 78, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = 78, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2009.75, y = 78, label = "Free Movement", hjust = 0.5) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"),
        axis.title.y = element_text(vjust = 0)) +
  ggtitle("A. Placebo Popular Votes")


placebo_did <- ggplot(coef.gg.prep(list(mod_did_yearFE_weights_placebo)), aes(x = modelcoef, y = -1*y, xmin = ylo95, xmax = yhi95, color = variable, shape = variable, group = variable)) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "black") +
  ggstance::geom_linerangeh(position = ggstance::position_dodgev(.25)) +
  ggstance::geom_pointrangeh(aes(xmin = ylo90, xmax = yhi90), size = 1.25, position = ggstance::position_dodgev(.25)) +
  ylab(NULL) +
  scale_y_continuous(breaks = c(-2, -1), labels = c("Transition\nPeriod", "Free\nMovement"), expand = expand_scale(mult = 0, add = 0.5)) +
  scale_color_manual(name = NULL, guide = "none", values = cbPalette[-3]) +
  scale_shape_discrete(name = NULL, guide = "none") +
  xlab("Effect of Border Proximity on Placebo Popular Votes") +
  ggtitle("C. Difference-in-Differences Estimates") +
  theme_bw() + 
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt"))


event_study_dat <- data.frame(
  y = coef(mod_es_year_FE_weights_placebo),
  ymin = coef(mod_es_year_FE_weights_placebo) - qt(.975, df = df.residual(mod_es_year_FE_weights_placebo))*sqrt(diag(vcov(mod_es_year_FE_weights_placebo))),
  ymax = coef(mod_es_year_FE_weights_placebo) + qt(.975, df = df.residual(mod_es_year_FE_weights_placebo))*sqrt(diag(vcov(mod_es_year_FE_weights_placebo))),
  Year = as.numeric(gsub("border[[:digit:]][[:digit:]]_", "", names(coefficients(mod_es_year_FE_weights_placebo))))
)

event_study_dat <- rbind(setDT(event_study_dat), data.table(c(0), c(0), c(0), c(1999)), use.names = F)

placebo_es <- ggplot(data = event_study_dat, aes(x = Year, y = y, ymin = ymin, ymax = ymax, 
                                                 color = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1))),
                                                 shape = factor(ifelse(Year <= 1999, 3, ifelse(Year < 2004, 2, 1)))
                                                 )) + 
  geom_vline(xintercept = c(1999, 2004), linetype = 2, color = "black") +
  geom_hline(yintercept = 0, linetype = 2, color = "black") +
  geom_pointrange() +
  annotate("text", x = 1995.5, y = 8, label = "Pre-Reform", hjust = 0.5) +
  annotate("text", x = 2001.5, y = 8, label = "Transition", hjust = 0.5) +
  annotate("text", x = 2009.75, y = 8, label = "Free Movement", hjust = 0.5) +
  scale_color_manual(values = cbPalette[c(1,2,8)], name = NULL, labels = c("Free Movement", "Transition", "Pre-Reform"), guide = guide_legend(reverse = T)) +
  scale_shape_manual(values = c(16, 17, 18), 
                     name = NULL, 
                     labels = c("Free Movement", "Transition", "Pre-Reform"), 
                     guide = guide_legend(reverse = T)) + 
  ylab("Change in Placebo Vote Share") +
  theme_minimal() + 
  scale_x_continuous(breaks = seq(1991, 2019,2)) +
  theme(legend.position = "bottom",
        legend.background = element_rect(color = "black"),
        legend.margin = margin(4,4,4,4,unit = "pt")) +
  ggtitle("B. Effect of Border Proximity By Year")


plots = align_patches(placebo_raw, placebo_did)
top_row = plot_grid(plots[[1]], placebo_es, align = "h")
pdf(here("figures", "Referendums_Placebo.pdf"), height = 8.27, width = 11.69)
plot_grid(top_row, plots[[2]], ncol = 1, rel_heights = c(3, 1.5))
dev.off()



# Output regressions ------------------------------------------------------
mod_did_topicFE %>% summary
mod_did_topicFE_weights %>% summary

mod_did_yearFE_placebo %>% summary
mod_did_yearFE_weights_placebo %>% summary

Texreg(
  list(mod_did_topicFE, mod_did_topicFE_weights, mod_did_yearFE, mod_did_yearFE_weights, mod_did_yearFE_placebo, mod_did_yearFE_weights_placebo),
  custom.header = list("Anti-immigrant vote" = 1:4, "Placebo vote" = 5:6),
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), 3),
                         "Fixed effects" = c("Referendum", "Referendum", "Year", "Year", "Referendum/Year", "Referendum/Year")
                         ),
  caption = "Effects on Voting Behavior in Immigration-Related and Placebo Popular Votes. Outcome: Percentage of Support for Anti-Immigrant and Placebo Votes. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1994--2017. Regression models include fixed effects for municipalities and either year or referendum. For the final two models, year and referendum fixed effects are equivalent. Regression weights are based on the electoral size of each municipality.",
  label = "tab:referendums_did",
  file = here("tables", "referendumsDID.tex")
)


new_labels <- list(
  "border15:date_topic1994-12-04 Bundesgesetz über Zwangsmassnahmen im Ausländerrecht" = "19941204 ZwangsmassAusl",
  "border15:date_topic1994-06-12 Bundesbeschluss über die Revision der Bürgerrechtsregelung in der Bundesverfassung (Erleichterte Einbürgerung für junge Ausländer)" = "19940612 BurgerrechtRev",
  "border15:date_topic1996-12-01 Volksinitiative «gegen die illegale Einwanderung»" = "19961201 VolksInitIllegEinw",
  "border15:date_topic1999-06-13 Bundesbeschluss über dringliche Massnahmen im Asyl- und Ausländerbereich" = "19990613 DringMassAsyl",
  "border15:date_topic2000-09-24 Volksinitiative «für eine Regelung der Zuwanderung»" = "20000924 VolksInitZuwander",
  "border15:date_topic2002-11-24 Volksinitiative «gegen Asylrechtsmissbrauch»" = "20021124 VolksInitAsylMiss",
  "border15:date_topic2004-09-26 Bundesbeschluss über den Bürgerrechtserwerb von Ausländerinnen und Ausländern der dritten Generation" = "20040926 BurgErw3Gen",
  "border15:date_topic2004-09-26 Bundesbeschluss über die ordentliche Einbürgerung sowie über die erleichterte Einbürgerung junger Ausländerinnen und Ausländer der zweiten Generation" = "20040926 OrdEinb2Gen",
  "border15:date_topic2005-09-25 Bundesbeschluss über die Ausdehnung des Personenfreizügigkeitsabkommens auf die neuen EU-Staaten und über die Revision der flankierenden Massnahmen" = "20050925 EUFreizugErw",
  "border15:date_topic2005-06-05 Bundesbeschluss über die Genehmigung und die Umsetzung der bilateralen Abkommen zwischen der Schweiz und der EU über die Assoziierung an Schengen und Dublin" = "20050605 EUAbkSchengenDublin",
  "border15:date_topic2006-09-24 Änderung des Asylgesetzes" = "20060924 AsyGAnd",
  "border15:date_topic2006-09-24 Bundesgesetz über die Ausländerinnen und Ausländer" = "20060924 AuslG",
  "border15:date_topic2008-06-01 Volksinitiative «Für demokratische Einbürgerungen»" = "20080601 DemEinb",
  "border15:date_topic2009-11-29 Volksinitiative «Gegen den Bau von Minaretten»" = "20091129 GegMinarette",
  "border15:date_topic2009-02-08 Weiterführung des Freizügigkeitsabkommens zwischen der CH und der EU sowie über die Genehmigung des Protokolls über die Ausdehnung des Abkommens auf Bulgarien und Rumänien" = "20090208 FreizugigkEU",
  "border15:date_topic2010-11-28 Volksinitiative «Für die Ausschaffung krimineller Ausländer»" = "20101128 VolksInitAusschaff",
  "border15:date_topic2013-06-09 Asylgesetz (AsylG) (Dringliche Änderungen des Asylgesetzes)" = "20130609 AsyGAnd",
  "border15:date_topic2014-11-30 Volksinitiative «Stopp der Überbevölkerung - zur Sicherung der natürlichen Lebensgrundlagen»" = "20141130 UberbevolkStop",
  "border15:date_topic2014-02-09 Volksinitiative «Gegen Masseneinwanderung»" = "20140209 GegMassenEinw",
  "border15:date_topic2016-06-05 Änderung des Asylgesetzes (AsylG)" = "20160605 AsyGAnd",
  "border15:date_topic2016-02-28 Volksinitiative «Zur Durchsetzung der Ausschaffung krimineller Ausländer (Durchsetzungsinitiative)»" = "20160228 DurchsetzInit",
  "border15:date_topic2017-02-12 Bundesbeschluss über die erleichterte Einbürgerung von Personen der dritten Ausländergeneration" = "20170212 Einb3Gen")

texreg(
  list(
    mod_es_topic_FE,
    mod_es_topic_FE_weights),
  omit.coef = "border15$|^(?!.*border15:date).*",
  custom.coef.map = new_labels,
  custom.gof.rows = list("Weights" = c("No", "Yes")),
  custom.header = list("Anti-Immigrant Vote at Referendum Level" = 1:2),
  caption = "Event Study of Voting Behavior in Immigration-Related Referendums and Popular Initiatives. Outcome: Percentage Support for Anti-Immigrant Votes in Each Referendum. Sample: Border Region, Travel Minutes $<=$ 30, 1994--2017. 
  The baseline referendum is the June 13, 1999, Bundesbeschluss \\\"uber dringliche Massnahmen im Asyl- und Ausl\\\"anderbereich (Federal Decision on Urgent Measures in the Asylum and Foreigners Sector). Weights are based on the electoral size of each municipality.",
  label = "tab:referendums_es_topic",
  file = here("tables", "referendums_es_topic.tex"),
  single.row = T,
  booktabs = T,
  dcolumn = T,
  caption.above = TRUE,
  use.packages = FALSE,
  include.rsquared = FALSE,
  include.adjrs = FALSE,
  float.pos = "h!"
)


new_coef_names <- c(names(coefficients(mod_es_year_FE)) %>% str_replace("border15_", "0--15 Minutes X "))


texreg(
  list(
    mod_es_year_FE,
    mod_es_year_FE_weights,
    mod_es_year_FE_placebo,
    mod_es_year_FE_weights_placebo
    
  ),
  custom.coef.names = new_coef_names,
  custom.gof.rows = list("Weights" = rep(c("No", "Yes"), 2)),
  custom.header = list("Anti-Immigrant Votes" = 1:2,
                       "Placebo Votes" = 3:4),
  caption = "Event Study of Voting Behavior in Immigration-Related Referendums and Popular Initiatives. Outcome: Percentage Support for Anti-Immigrant and Placebo Votes Per Year. 
  Sample: Border Region, Travel Minutes $<=$ 30, 1994--2017. The baseline year is 1999. Weights are based on the electoral size of each municipality.",
  label = "tab:referendums_es_year",
  file = here("tables", "referendums_es_year.tex"),
  single.row = T,
  booktabs = T,
  dcolumn = T,
  caption.above = TRUE,
  use.packages = FALSE,
  include.rsquared = FALSE,
  include.adjrs = FALSE,
  float.pos = "h!"
)
